package cn.jiahua.test6;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *  A 和  B 操作同一个变量   num=0;
 * A是生产者   num+1
 * B是消费者   num-1
 * Synchronzied 实现
 */
public class Test {

    public static void main(String[] args) {
        Data data=new Data();

        new Thread(()->{
            for (int i=0;i<15;i++){
                data.incrementA();
            }
        },"A").start();

        new Thread(()->{
            for (int i=0;i<15;i++){
                data.decrementB();
            }
        },"B").start();


        new Thread(()->{
            for (int i=0;i<15;i++){
                data.incrementC();
            }
        },"C").start();

        new Thread(()->{
            for (int i=0;i<15;i++){
                data.decrementD();
            }
        },"D").start();

    }

}

class Data{
    private int number=0;
    Lock lock =new ReentrantLock();
    Condition conditionA =lock.newCondition();  //生产者 消费者
    Condition conditionB =lock.newCondition();
    Condition conditionC =lock.newCondition();  //生产者 消费者
    Condition conditionD =lock.newCondition();


    private int num=1;

    public void incrementA(){
        lock.lock();
        try {
            while(num!=1){
                conditionA.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName() + "===》生产者放入数据了" + number);
            num=2;
            conditionB.signal();
        }catch (Exception e){
            e.printStackTrace();

        }finally {
            lock.unlock();
        }
    }


    public void decrementB(){
        lock.lock();

        try {
            while (num!=2) {
                conditionB.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "===》消费者消费数据" + number);
            conditionC.signal();
            num=3;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }



    public void incrementC()  {
        lock.lock();
        try {
            while (num != 3) {
                conditionC.await();
            }

            number++;
            System.out.println(Thread.currentThread().getName() + "===》生产者放入数据了" + number);
            num = 4;
            conditionD.signal();
        }catch (Exception e){

            e.printStackTrace();

        }finally {
            lock.unlock();
        }

    }


    public void decrementD(){
        lock.lock();

        try {
            while (num !=4) {
                conditionD.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "===》消费者消费数据" + number);
            conditionA.signal();
            num=1;

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }



}
